{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "Chapter 07\n",
    "# 复刻numpy.linspace() 基本功能\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "# 自定义函数模仿 numpy.linspace()\n",
    "def linspace(start, stop, num=50, endpoint=True):\n",
    "    if num < 2:\n",
    "        # 报错\n",
    "        raise ValueError(\"Number of samples must be at least 2\")\n",
    "    # 是否包括右端点\n",
    "    if endpoint:\n",
    "        step = (stop - start) / (num - 1)\n",
    "        return [start + i * step for i in range(num)]\n",
    "    else:\n",
    "        step = (stop - start) / num\n",
    "        return [start + i * step for i in range(num)]"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:53:49.648071Z",
     "end_time": "2024-07-03T10:53:49.652919Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "# 示例用法\n",
    "start = 0  # 数列起点\n",
    "stop = 10  # 数列终点\n",
    "num = 21  # 数列元素\n",
    "endpoint = True  # 数列包含 stop\n",
    "# 调用自定义函数生成等差数列\n",
    "values = linspace(start, stop, num, endpoint)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:54:22.717096Z",
     "end_time": "2024-07-03T10:54:22.769141Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "data": {
      "text/plain": "[0.0,\n 0.5,\n 1.0,\n 1.5,\n 2.0,\n 2.5,\n 3.0,\n 3.5,\n 4.0,\n 4.5,\n 5.0,\n 5.5,\n 6.0,\n 6.5,\n 7.0,\n 7.5,\n 8.0,\n 8.5,\n 9.0,\n 9.5,\n 10.0]"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T10:54:35.018065Z",
     "end_time": "2024-07-03T10:54:35.028432Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
